package com.kakarote.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.UserInfo;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.crm.entity.CrmSearchBO;
import com.kakarote.core.feign.examine.entity.ExamineInfoVo;
import com.kakarote.core.feign.examine.service.ExamineService;
import com.kakarote.core.feign.oa.entity.OaExamineVO;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.ESConditionToSqlUtil;
import com.kakarote.core.utils.UserCacheUtil;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.oa.common.ExamineFlagEnum;
import com.kakarote.oa.common.OaCodeEnum;
import com.kakarote.oa.entity.BO.AuditExamineBO;
import com.kakarote.oa.entity.BO.ExamineDraftPageBO;
import com.kakarote.oa.entity.BO.OaSearchBO;
import com.kakarote.oa.entity.PO.OaExamine;
import com.kakarote.oa.entity.VO.ExamineVO;
import com.kakarote.oa.mapper.OaExamineMapper;
import com.kakarote.oa.service.IOaSuperExamineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 审批表 服务实现类
 * </p>
 *
 * @author wyq
 * @since 2020-05-15
 */
@Service
public class OaSuperExamineServiceImpl extends BaseServiceImpl<OaExamineMapper, OaExamine> implements IOaSuperExamineService {

    @Autowired
    private ExamineService examineService;

    @Autowired
    private OaExamineMapper examineMapper;

    @Autowired
    private OaExamineServiceImpl oaExamineServiceImpl;

    /**
     * 功能描述: <br>
     * 〈获取抄送给我列表数据〉
     *
     * @param:
     * @return: com.kakarote.core.common.Result<java.util.List < java.util.Map < java.lang.String, java.lang.Object>>>
     * @throws:
     * @author: zyh
     * @date: 2022/8/27 11:19
     */
    @Override
    public BasePage<ExamineVO> selectDraftOaEaminePage(ExamineDraftPageBO searchBO) {
        //查询所有的草稿审批
        Map<String, String> oaSqlMap = getOaSqlMap(searchBO);

        BasePage<OaExamine> basePage = examineMapper.selectDraftPage(searchBO.parse(), ExamineFlagEnum.DRAFT.getType(), searchBO, oaSqlMap, UserUtil.getUserId());
        List<ExamineVO> examineVOs = new ArrayList<>();
        //数据组装
        if (CollectionUtil.isNotEmpty(basePage.getList())) {
            for (OaExamine oaExamine : basePage.getList()) {
                ExamineVO examineVO = oaExamineServiceImpl.getOaExamineById(oaExamine.getExamineId());
                examineVOs.add(examineVO);
            }
        }
        BasePage<ExamineVO> page = new BasePage<>(basePage.getCurrent(), basePage.getSize(), basePage.getTotal());
        page.setList(examineVOs);
        return page;
    }

    /**
     * 功能描述：根据审批事由查询OA模块审批列表
     *
     * @param content
     * @return
     */
    @Override
    public List<com.kakarote.core.feign.oa.entity.OaExamine> queryExamineByName(String content) {
        List<com.kakarote.core.feign.oa.entity.OaExamine> result = new ArrayList<>();
        List<OaExamine> oaExamineList = lambdaQuery().select().like(OaExamine::getContent, content).list();
        if (CollectionUtil.isNotEmpty(oaExamineList)) {
            oaExamineList.forEach(
                    oaExamine -> {
                        com.kakarote.core.feign.oa.entity.OaExamine oaExamineCore = new com.kakarote.core.feign.oa.entity.OaExamine();
                        BeanUtil.copyProperties(oaExamine, oaExamineCore);
                        if (ObjectUtil.isNotEmpty(oaExamine.getExamineRecordId())) {
                            result.add(oaExamineCore);
                        }
                    }
            );
        }
        return result;
    }

    /**
     * 待办详情
     */
    @Override
    public OaExamineVO getExamineInfo(Long examineId) {
        OaExamine oaExamine = examineMapper.selectById(examineId);

        if (ObjectUtil.isEmpty(oaExamine)) {
            throw new CrmException(OaCodeEnum.EXAMINE_ALREADY_DELETE);
        }
        String handled = oaExamine.getHandled();
        List<UserInfo> userInfoList = new ArrayList<>();
        if (StringUtil.isNotEmpty(handled)) {
            List<String> userList = Arrays.asList(handled.split(","));
            if (CollectionUtil.isNotEmpty(userList)) {
                for (String userId : userList) {
                    UserInfo userInfo = UserCacheUtil.getUserInfo(Long.parseLong(userId));
                    userInfoList.add(userInfo);
                }
            }
        }
        ExamineInfoVo examineInfoVo = examineService.queryExamineById(oaExamine.getCategoryId()).getData();
        OaExamineVO examineVO = new OaExamineVO();
        BeanUtil.copyProperties(oaExamine, examineVO);
        examineVO.setCategoryType(examineInfoVo.getExamineName());
        UserInfo submitUser = UserCacheUtil.getUserInfo(oaExamine.getCreateUserId());
        examineVO.setSubmitUser(submitUser);
        examineVO.setHandledList(userInfoList);
        //返回对象先空置，后续页面完善再获取
        return examineVO;
    }

    @Override
    public BasePage<com.kakarote.core.feign.oa.entity.OaExamine> queryExamineByNameForPage(OaSearchBO oaSearchBO) {
        return getBaseMapper().queryExamineByNameForPage(oaSearchBO.parse(), oaSearchBO);
    }

    @Override
    public void actionExamine(AuditExamineBO auditExamineBO) {
        if (ObjectUtil.isEmpty(auditExamineBO.getRecordId())) {
            throw new CrmException(OaCodeEnum.OA_EXAMINE_PARAM_ERROR);
        }
        if (!Arrays.asList(ExamineFlagEnum.END.getType(), ExamineFlagEnum.VOID.getType()).contains(auditExamineBO.getArchiveOrVoidFlag())) {
            throw new CrmException(OaCodeEnum.OA_EXAMINE_PARAM_ERROR);
        }

        List<OaExamine> list = lambdaQuery().eq(OaExamine::getExamineRecordId, auditExamineBO.getRecordId()).list();
        if (CollectionUtil.isNotEmpty(list)) {
            OaExamine oaExamine = list.get(0);
            switch (ExamineFlagEnum.valueOf(auditExamineBO.getArchiveOrVoidFlag())) {
                case NORMAL:
                    break;
                case DRAFT:
                    break;
                case SUBMITTED:
                    break;
                case END:
                    oaExamine.setExamineFlag(ExamineFlagEnum.END.getType());
                    break;
                case VOID:
                    oaExamine.setExamineFlag(ExamineFlagEnum.VOID.getType());
                    oaExamine.setExamineStatus(8);
                    break;
                default:
                    break;
            }
            saveOrUpdate(oaExamine);
            //掉用审批执行
        }
    }

    public Map<String, String> getOaSqlMap(CrmSearchBO searchBO) {
        Map<String, String> sqlMap = new HashMap<>();
        List<String> oaExamineField = getOaExamineField();
        List<String> wkExamineField = getWkExamineField();
        ESConditionToSqlUtil toSqlUtil = new ESConditionToSqlUtil();
        Map<String, String> oaNamePrefixMap = toSqlUtil.getFieldNamePrefixMap(oaExamineField, "oe");
        Map<String, String> wkNamePrefixMap = toSqlUtil.getFieldNamePrefixMap(wkExamineField, "e");
        String oaEsToSql = toSqlUtil.searchESToSql(searchBO, oaNamePrefixMap);
        String wkEsToSql = toSqlUtil.searchESToSql(searchBO, wkNamePrefixMap);
        sqlMap.put("oe", oaEsToSql);
        sqlMap.put("e", wkEsToSql);
        return sqlMap;
    }

    public List<String> getOaExamineField() {
        List<String> fields = new ArrayList<>();
        fields.add("content");
        fields.add("submit_dept_id");
        fields.add("create_time");
        return fields;
    }

    public List<String> getWkExamineField() {
        List<String> fields = new ArrayList<>();
        fields.add("examine_name");
        return fields;
    }
}
